"""
TODO: Massive rewrite this code is ugly!!!
"""

def baseUrl(url):
    ## Gather the base url
    url = url.split("/")[0:3]

    ## Remove cased letters in the URL
    link = ""
    for i,part in enumerate(url):
        link += part.lower()+"/"
    return link

def subUrl(base,sub):
	if len(sub) > 0:
		#print "\tStart:\t",base,"\t",sub
		if sub== "./":
			return base
		if sub=="/":
			return "/".join(base.split("/")[:3])+"/"
		if sub[0:2] == "./":
			sub = sub[2:]
		if sub[0] == "/" and base.find("?") == -1: # Get rid of the redunent
		    sub = sub[1:]
		if sub[-1] == "/" and sub[0] != "/": #this is a relative link
		    base = base.split("?")[0]
		if sub[0] == "/" and base.find("?") == -1:
		    base = base.split("?")[0]
		if sub[0] == "?" and base.find("?") >= 0: #If there is a starting argument already!
		    base = base.split("?")[0] ## Strip it
		if sub[0] != "/" and base.find("?") >= 0 and sub.find("?") >= 0:
		    base = base.split("?")[0]
		    sub = "?"+sub.split("?")[1]
		if sub[0] != "/" and base.find("?") >= 0 and sub.find("?") != 0:
			bases = base.split("/")[:-1]
			base = ""
			for subbase in bases:
				base += subbase+"/"
		if base[-1] != "/" and sub[0] != "/" and sub.find("?") == -1:
		    if sub.find(".") == -1:
			bases = base.split("/")[:-1]
			base = ""
			for subbase in bases:
			    base += subbase+"/"
		    else:
			if base.split("/")[-1].find(".") > -1:
			    bases = base.split("/")[:-1]
			    base = ""
			    for subbase in bases:
				base += subbase+"/"               
			else:
			    base += "/"
		if sub[-1] != "/" and sub.find("?") == -1:
		    if base.split("/")[-1].find(".") > -1:
			sub += "/"
		    else:
			baseSplit = base.split("/")
			if len(baseSplit) < 5:
			    if sub.find(".") == -1:
				sub += "/"
		## RELATIVE BACK TRACKING
		if sub.find("../") > -1:
		    subSplit = sub.split("../")
		    traceBack = int("-"+str(len(subSplit)))
		    bases = base.split("/")[:traceBack]
		    base = ""
		    sub = sub.replace("../", "")
		    for subbase in bases:
			base += subbase+"/" 
		    
		if sub.find("javascript:") > -1: #email address ewww ?archive
		    sub = ""
		if len(sub) > 0 and sub[0] == "#": #anchor ewww
		    sub = ""
		if len(sub) > 0 and sub.split("/")[-1].find("#") > -1: #anchor ewww
		    print sub.split("/")
		if sub.find("mailto:") > -1: #email address ewww ?archive
		    sub = ""
		if sub.find("sms:") > -1: #phone text message ewww
		    sub = ""
		if sub.find("file:") > -1: #local file ewww
		    sub = ""
		sub = sub.replace(" ", "%20")
		if sub == "%20/":
		    sub = ""
		
		#print "\tEnd:\t",base,"\t",sub
		return base+sub

